/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package DAO.InformationFilter;

import DAO.DAOAccess;
import Info.UserInfo;
import MySqlAccess.DataAcessHelper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author tran tuan tai
 */
public class UserDAO
{

     public void DoEmpty()
    {
         try
        {
            java.sql.Connection conn = DAOAccess.GetConnection();
            String sql = "DELETE FROM USER";
            PreparedStatement stat = conn.prepareCall(sql);
            stat.execute();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

    public void Insert(List<UserInfo> lstUser)
    {
        java.sql.Connection conn = DAOAccess.GetConnection();
        String sql = "INSERT INTO user(USERID, REGISTERDATE) VALUES(?, ?)";
        try
        {
            for (UserInfo user : lstUser)
            {
                PreparedStatement stat = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
                stat.setInt(1, user.id);
                stat.setTimestamp(2, user.registeredDate);

                stat.executeUpdate();
                ResultSet result = stat.getGeneratedKeys();
                result.first();

                stat.close();
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }


    public List<UserInfo> GetAll()
    {
        String query = "SELECT * FROM USER";
        return ExcuteQuery(query);
    }
    public List<UserInfo> ExcuteQuery(String query)
    {
        List<UserInfo> result = new ArrayList<UserInfo>();

        try
        {
            ResultSet rs =  DAOAccess.ExcuteQuery(query);

            //int idxContent = rs.findColumn("post_content");
            int idxID = rs.findColumn("USERID");
            int idxRegisterDate = rs.findColumn("REGISTERDATE");
            //int idxPosDate = rs.findColumn("POST_DATE");

            rs.beforeFirst();

            while(rs.next())
            {
                UserInfo info = new UserInfo();
                info.id = rs.getInt(idxID);
                info.registeredDate = rs.getTimestamp(idxRegisterDate);
                
                result.add(info);
            }
            rs.close();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }

        return result;
    }
}
